package spring.security.core.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SerializeUtils {
	
	private static final Logger LOG = LoggerFactory.getLogger(SerializeUtils.class);
	//private static final int BUFFER_SIZE = 128;

	public static Object deserialize(byte[] bytes) {
		if (isEmpty(bytes)) {
			return null;
		} else {
			try {
				ByteArrayInputStream e = new ByteArrayInputStream(bytes);
				ObjectInputStream objectInputStream = new ObjectInputStream(e);
				return objectInputStream.readObject();
			} catch (ClassNotFoundException arg2) {
				LOG.error("Failed to deserialize", arg2);
			} catch (IOException arg3) {
				LOG.error("Failed to deserialize", arg3);
			}

			return null;
		}
	}

	@SuppressWarnings("unchecked")
	public static <T> T deserialize(byte[] bytes, Class<T> clazz) {
		return (T) deserialize(bytes);
	}

	public static byte[] serialize(Object object) {
		if (object == null) {
			return new byte[0];
		} else {
			try {
				ByteArrayOutputStream ex = new ByteArrayOutputStream(128);
				if (!(object instanceof Serializable)) {
					throw new IllegalArgumentException(SerializeUtils.class.getSimpleName()
							+ " requires a Serializable payload but received an object of type ["
							+ object.getClass().getName() + "]");
				} else {
					ObjectOutputStream objectOutputStream = new ObjectOutputStream(ex);
					objectOutputStream.writeObject(object);
					objectOutputStream.flush();
					return ex.toByteArray();
				}
			} catch (IOException arg2) {
				LOG.error("Failed to serialize", arg2);
				return new byte[0];
			}
		}
	}

	public static boolean isEmpty(byte[] data) {
		return ArrayUtils.isEmpty(data);
	}
	
}
